import format from "date-fns/format";
const startTime = Date.now();

export function isOneMinu() {
  const now = Date.now();
  const oneM = 60 * 1000;
  return !(now - startTime < oneM);
}



/**
 * 获取地址栏参数
 */
 export function getUrlParams() {
  const url = window.location.href;
  if ("undefined" == url) {
    return {};
  }
  let paraString = url.substring(url.indexOf("?") + 1, url.length).split("&");
  let paraObj = {};
  if (paraString == url) {
    return "";
  }
  for (let i = 0; i < paraString.length; i++) {
    let j = paraString[i];
    paraObj[j.substring(0, j.indexOf("="))] = j.substring(
      j.indexOf("=") + 1,
      j.length
    );
  }
  return paraObj;
}

/**
 * 富文本框内容img路径处理
 * 
 */
export function imgPath(data) {
  
  const reg = /<img [^>]*src=['"]([^'"]+)[^>]*>/gi;
  var regExp = window.location.href;
  let urlPath = "";
  switch (true) {
    case regExp.indexOf("test") > -1||regExp.indexOf("localhost") > -1:
      // urlPath = "http://product-test.zx093.com";
      urlPath = "http://product.zx093.com";
      break;
    case /http:\/\/app-dev.zx093.com/.test(regExp):
      urlPath = "http://product-dev.zx093.com";
      break;
    case /http:\/\/client.zx093.com/.test(regExp):
      urlPath = "http://product.zx093.com";
      break;
  }
  if(!data)return;
  return data.replace(reg, (img, url) =>
    url.indexOf("http") != -1
      ? `<img src="${url}" onerror="this.src='${url}'; this.onerror = null " />`
      : `<img src="${urlPath + url}" onerror="javascript:this.src='${urlPath + url}'; this.onerror = null "/>`
  );
  
}
/**
 * 时间格式 今天、昨天、前天
 */
export function timeFormat(timestamp, reg) {
  let result;

  //获取昨天
  const getYesterday = function() {
    var day1 = new Date();
    day1.setTime(day1.getTime() - 24 * 60 * 60 * 1000);
    var s1 = day1.getFullYear() + "-" + (day1.getMonth() + 1) + "-" + day1.getDate();
    return s1;
  };

  //获取前天天
  const beforeYesterday = function() {
    var day1 = new Date();
    day1.setTime(day1.getTime() - 24 * 60 * 60 * 1000 * 2);
    var s1 = day1.getFullYear() + "-" + (day1.getMonth() + 1) + "-" + day1.getDate();
    return s1;
  };
  //日期获取毫秒数
  const getSeconds = function(date) {
    var time = new Date(date.replace(/-/g, "/"));
    var seconds = time.getTime();
    return seconds;
  };
  const yesterdayStart = getSeconds(getYesterday() + " " + "00:00:00"); //昨天开始时间
  const yesterdayEnd = getSeconds(getYesterday() + " " + "23:59:59"); //昨天结束时间
  const beforeyesterdayStart = getSeconds(beforeYesterday() + " " + "00:00:00"); //前天开始时间
  const beforeyesterdayEnd = getSeconds(beforeYesterday() + " " + "23:59:59"); //前天结束时间
  if (timestamp > yesterdayEnd) {
    result = "今天 " + format(new Date(timestamp), "HH:mm");
  } else if (timestamp >= yesterdayStart && timestamp <= yesterdayEnd) {
    result = "昨天 " + format(new Date(timestamp), "HH:mm");
  } else if (timestamp >= beforeyesterdayStart && timestamp <= beforeyesterdayEnd) {
    result = "前天 " + format(new Date(timestamp), "HH:mm");
  } else {
    result = format(new Date(timestamp), reg ? reg : "yyyy-MM-dd HH:mm");
  }
  return result;
}
//跳转实时行情
export function stockMarker(code, type, block) {
  const setcode = code.match(/(\w)+$/g)[0] == "SZ" ? "0" : "1";
  type = type == undefined ? "" : type;
  if (block) {
    code = code.match(/\d{6}$/)[0];
  } else {
    code = code.match(/\d{6}/)[0];
  }
  console.log(setcode, code, type);
  window.prompt(
    "",
    `up://["open.stock",${Date.now()},{"setcode":"${
      block ? block : setcode
    }","code":"${code}","type":"${type}"}]`
  );
}
//相关板块
export function blockStock(data) {
  const { hotspotName, block, stock } = data;
  window.prompt(
    "",
    `up://["user.info",${Date.now()},{"type":"风口","data":{"hotspotName":"${hotspotName}","block":${block},"stock":${stock}}}]`
  );
}
//图片错误重新加载
export function imageHandler(imgPath, e) {
  console.log(imgPath);
  const img = e.srcElement;
  img.src = imgPath;
}


/**
 * 创建socket连接通道
 */
 export function creatSocket(key, back) {
  try {
    let webSocket;
    const host = path.replace("http:", "");
    const webSocketPath = "ws:" + host + "/websocket";
    console.log(webSocketPath);
    webSocket = new ReconnectingWebSocket(webSocketPath);
    webSocket.debug = true;
    webSocket.timeoutInterval = 5400;
    window.onbeforeunload = function() {
      webSocket.close();
    };

    webSocket.onopen = function(event) {
      webSocket.send(key);
    };
    webSocket.onmessage = function(event) {
      const _data = eval("(" + event.data + ")");
      console.log("push", _data);
      back(_data);
      //互动信息
      //if (dataType == "2") {
      //    chat.onSocket(_data);
      //}
    };
  } catch (e) {
    console.log("use timer update data...");
    //IE8使用定时器更新数据
  }
}
/**
 * 表情解码
 */
 export function entitiestoUtf16(str) {
  // 检测出形如&#12345;形式的字符串
  const strObj = utf16toEntities(str);
  const patt = /&#\d+;/g;
  let H, L, code;
  const arr = strObj.match(patt) || [];
  for (let i = 0; i < arr.length; i++) {
    code = arr[i];
    code = code.replace("&#", "").replace(";", "");
    // 高位
    H = Math.floor((code - 0x10000) / 0x400) + 0xd800;
    // 低位  
    L = ((code - 0x10000) % 0x400) + 0xdc00;
    code = "&#" + code + ";";
    const s = String.fromCharCode(H, L);
    strObj.replace(code, s);
  }
  return strObj;
}

//股票高亮
export function higihLighttStock(str) {
  function createPlainStock(code, market, stockCode) {
    const attribute = market ? ` data-market="${market}"` : "";
    const stockcode = stockCode ? `data-code="${stockCode}"` : "";
    return `<span ${attribute} ${stockcode} class="_stockCode">${code}</span>`;
  }
  //股票高亮
  str = str.replace(/\$.+?\$/g, (text) => {
    /**匹配marketShortCode */
    const reg = /\$([A-Z]+)-/;
    if (!reg.test(text)) {
      return createPlainStock(text);
    }
    const marketCode = text.match(reg)[1];
    const code = text.replace(reg, "$");

    /**匹配股票代码 */
    const codeReg = /\$[A-Z]+-([0-9]{6})/;
    const stockCode = text.match(codeReg)[1];
    return createPlainStock(code, marketCode, stockCode);
  });
  return str;
}

/**
 * 表情储存
 */
 export function utf16toEntities(str) {
  const patt = /[\ud800-\udbff][\udc00-\udfff]/g;
  // 检测utf16字符正则
  str = str.replace(patt, function(char) {
    let H, L, code;
    if (char.length === 2) {
      H = char.charCodeAt(0);
      // 取出高位
      L = char.charCodeAt(1);
      // 取出低位
      code = (H - 0xd800) * 0x400 + 0x10000 + L - 0xdc00;
      // 转换算法
      return "&#" + code + ";";
    } else {
      return char;
    }
  });
  return str;
}
